﻿/*
 *  ChgDoc CMS - GNU General Public License, version 3 (GPL-3.0)
 *  Copyright (C)  2012. Ian Quigley
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ChgDoc.Entity;
using System.Collections;
using System.Reflection;
using System.Collections.Concurrent;

namespace ChgDoc.Edit
{
	[AdminPage("Edit settings", "Admin")]
	public partial class ConfigEdit : BasePage
	{
		protected override IEnumerable<FormRule> GetFormRules()
		{
			return new List<FormRuleMapping<Settings>>()
			       	{
			       		new FormRuleMapping<Settings>( txtName, "Name", FormRuleCondition.NotNull, (s,v) => s.Name = (string)v),
						new FormRuleMapping<Settings>( txtValue, "Value", FormRuleCondition.NotNull, (s,v) => s.Value = (string)v)
			       	};
		}

		protected void Page_Load( object sender, EventArgs e )
		{
			if (IsPostBack)
				return;

			UpdateDisplay();
		}

		private void UpdateDisplay( )
		{
			grdSettings.DataSource = Settings.ReadAll();
			grdSettings.DataBind();
		}

		protected void grdSettings_ItemCommand(object source, DataGridCommandEventArgs e)
		{
			
		}

		protected void grdSettings_Edit(object source, DataGridCommandEventArgs e)
		{
			grdSettings.EditItemIndex = e.Item.ItemIndex;
			UpdateDisplay();
		}

		protected void grdSettings_Cancel(object source, DataGridCommandEventArgs e)
		{
			grdSettings.EditItemIndex = -1;
			UpdateDisplay();
		}

		protected void grdSettings_Update(object source, DataGridCommandEventArgs e)
		{
            Config.Current[e.Item.Cells[0].Text] = ((TextBox)e.Item.Cells[1].Controls[0]).Text;
			grdSettings.EditItemIndex = -1;
			UpdateDisplay();
		}

		protected void btnSave_Click(object sender, EventArgs e)
		{
			Settings model = new Settings();
			if (!PopulateModelFromControls<Settings>(model))
				return;

            Settings.SetValue( model.Name, model.Value );
			UpdateDisplay();
		}

		protected void grdSettings_Command(object source, DataGridCommandEventArgs e)
		{
			if (e.CommandName != "Delete")
				return;

			Settings.Delete( e.Item.Cells[ 0 ].Text );
			UpdateDisplay();
		}
	}
}